package com.pzhu.controller;

import com.alibaba.excel.EasyExcel;
import com.pzhu.utils.User;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author : zqh
 * @Date : 2023/12/26 0026 上午 11:13
 * @Version: 1.0
 */
@Controller
public class ExportController {

    @GetMapping("/download-excel")
    @ResponseBody
    public ResponseEntity<byte[]> downloadExcel() {
        // 创建用户数据
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "张三", new Date()));
        userList.add(new User(2, "李四", new Date()));

        // 写入到 ByteArrayOutputStream
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream, User.class).sheet("Sheet1").doWrite(userList);

        try {
            // 将 ByteArrayOutputStream 转为 byte 数组
            byte[] byteArray = outputStream.toByteArray();
            outputStream.close();

            // 构建 HTTP 响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "output.xlsx");

            // 使用 HttpStatus.OK 表示成功
            return new ResponseEntity<>(byteArray, headers, HttpStatus.OK);
        } catch (IOException e) {
            // 处理异常，使用 HttpStatus.INTERNAL_SERVER_ERROR 表示服务器内部错误
            return new ResponseEntity<>(null, null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
